<template>
  <div>
    <div>
      <div style="display: flex;justify-content: space-between">
        <div>
          <el-input prefix-icon="el-icon-search"
                    placeholder="请输入学生姓名进行搜索..."
                    v-model="studentName"
                    @keydown.enter.native="initStuInfos"
                    clearable
                    @clear="initStuInfos"
                    :disabled="showAdvanceSearchVisible"
                    style="width: 300px;margin-right: 10px"></el-input>
          <el-button type="primary"
                     icon="el-icon-search"
                     @click="initStuInfos"
                     :disabled="showAdvanceSearchVisible">搜索
          </el-button>
          <el-button type="primary"
                     @click="showAdvanceSearchView">
            <i :class="showAdvanceSearchVisible?'fa fa-angle-double-up':'fa fa-angle-double-down'"
               aria-hidden="true"></i>
            高级搜索
          </el-button>
        </div>
        <div>
          <el-upload
              action="/student/punish/import"
              :before-upload="beforeUpload"
              :headers="headers"
              :on-success="onSuccess"
              :on-error="onError"
              :disabled="importDataDisabled"
              style="display: inline-flex;margin-right: 8px"
              :show-file-list="false">
            <el-button :disabled="importDataDisabled" type="success"
                       :icon="importDataBtnIcon">
              {{ importDataBtnText }}
            </el-button>
          </el-upload>
          <el-button type="success" @click="exportData" icon="el-icon-download">
            导出数据
          </el-button>
          <el-button type="primary" icon="el-icon-plus" @click="showAddStudentView">
            添加学生惩处信息
          </el-button>
        </div>
      </div>
      <transition name="slide-fade">
        <div v-show="showAdvanceSearchVisible"
             style="border: 1px solid #409eff;border-radius: 5px;box-sizing:border-box;padding: 5px;margin: 10px 0px">
          <el-row>
            <el-col :span="4">
              民族:
              <el-select v-model="searchValue.nationId"
                         placeholder="民族" size="mini" style="width: 130px">
                <el-option
                    v-for="item in nations"
                    :key="item.id"
                    :label="item.name"
                    :value="item.id">
                </el-option>
              </el-select>
            </el-col>

            <el-col :span="4">
              专业:
              <el-select v-model="searchValue.majorId"
                         placeholder="专业" size="mini" style="width: 130px">
                <el-option
                    v-for="item in majors"
                    :key="item.id"
                    :label="item.name"
                    :value="item.id">
                </el-option>
              </el-select>
            </el-col>
            <el-col :span="4">
              学院:
              <el-select v-model="searchValue.departmentId"
                         placeholder="学院" size="mini" style="width: 130px">
                <el-option
                    v-for="item in departments"
                    :key="item.id"
                    :label="item.name"
                    :value="item.id">
                </el-option>
              </el-select>
            </el-col>
            <el-col :span="4" >
              <el-button @click="NOShowAdvanceSearchView">取消</el-button>
              <el-button type="primary"
                         @click="initStuInfos('advanced')">搜索
              </el-button>
            </el-col>
          </el-row>
        </div>
      </transition>
    </div>
    <div style="margin-top: 10px">
      <el-table
          :data="studentInfos"
          stripe
          border
          v-loading="loading"
          element-loading-text="正在加载..."
          element-loading-spinner="el-icon-loading"
          element-loading-background="rgba(0, 0, 0, 0.8)"
          style="width: 100%">
        <el-table-column
            type="selection"
            width="55">
        </el-table-column>
        <el-table-column
            prop="id"
            label="序号"
            fixed
            align="left"
            width="55">
        </el-table-column>
        <el-table-column
            prop="name"
            label="姓名"
            fixed
            align="left"
            width="85">
        </el-table-column>
        <el-table-column
            prop="s_number"
            label="学号"
            align="left"
            width="100">
        </el-table-column>
        <el-table-column
            prop="nation.name"
            width="70"
            label="民族">
        </el-table-column>
        <el-table-column
            prop="sex"
            label="性别"
            width="70">
        </el-table-column>
        <el-table-column
            prop="grade"
            align="left"
            width="95"
            label="所在年级">
        </el-table-column>
        <el-table-column
            prop="s_level"
            width="75"
            label="学历层次">
        </el-table-column>
        <el-table-column
            prop="s_category"
            width="90"
            label="学生类别">
        </el-table-column>
        <el-table-column
            prop="department.name"
            width="150"
            label="所在学院">
        </el-table-column>
        <el-table-column
            prop="major.name"
            width="90"
            label="专业名称">
        </el-table-column>
        <el-table-column
            prop="punishment_info"
            align="left"
            width="95"
            label="惩处信息">
        </el-table-column>
        <el-table-column
            prop="punishment_time"
            align="left"
            width="95"
            label="惩处日期">
        </el-table-column>
        <el-table-column
            prop="punishment_type"
            width="100"
            label="处罚类别">
        </el-table-column>
        <el-table-column
            prop="punishment_department"
            width="100"
            label="处罚部门">
        </el-table-column>
        <el-table-column
            fixed="right"
            width="200"
            label="操作">
          <template slot-scope="scope">
            <el-button style="padding: 3px" size="mini"
                       @click="showEditStudentView(scope.row)">编辑
            </el-button>
            <el-button style="padding: 3px" size="mini"
                       type="primary" @click="computeHashCode(scope.row)">生成hash值
            </el-button>
            <el-button style="padding: 3px" size="mini"
                       type="danger" @click="deleteStudent(scope.row)">删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>
      <div style="display: flex;justify-content: flex-end">
        <el-pagination
            background
            @current-change="currentChange"
            @size-change="sizeChange"
            layout="sizes,prev,pager,next,jumper,->,total,slot" :total="total"></el-pagination>
      </div>
    </div>

    <el-dialog
        :title="title"
        :visible.sync="dialogVisible"
        width="80%">
      <div>
        <el-form :model="student" :rules="rules" ref="studentForm">
          <el-row>
            <el-col :span="6">
              <el-form-item label="学号：" prop="s_number">
                <el-input size="mini" style="width: 150px" v-model="student.s_number" placeholder="请输入学号"
                          prefix-icon="el-icon-edit"></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="6">
              <el-form-item label="姓名：" prop="name">
                <el-input size="mini" style="width: 150px" v-model="student.name" placeholder="请输入学生姓名"
                          prefix-icon="el-icon-edit"></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="6">
              <el-form-item label="民族：" prop="nationId">
                <el-select v-model="student.nationId"
                           placeholder="民族" size="mini" style="width: 150px">
                  <el-option
                      v-for="item in nations"
                      :key="item.id"
                      :label="item.name"
                      :value="item.id">
                  </el-option>
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="6">
              <el-form-item label="性别：" prop="sex" >
                <el-radio-group v-model="student.sex" style="margin-top: 10px;">
                  <el-radio label="男">男</el-radio>
                  <el-radio label="女">女</el-radio>
                </el-radio-group>
              </el-form-item>
            </el-col>
          </el-row>

          <el-row>
            <el-col :span="6">
              <el-form-item label="所在年级：" prop="grade">
                <el-input size="mini" style="width: 120px" v-model="student.grade" placeholder="请输入所在年级"
                          prefix-icon="el-icon-edit"></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="6">
              <el-form-item label="学历层次：" prop="s_level">
                <el-select v-model="student.s_level"
                           placeholder="学历层次" size="mini" style="width: 150px">
                  <el-option
                      v-for="item in s_levels"
                      :key="item"
                      :label="item"
                      :value="item">
                  </el-option>
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="6">
              <el-form-item label="学生类别：" prop="s_category">
                <el-select v-model="student.s_category"
                           placeholder="学生类别" size="mini" style="width: 150px">
                  <el-option
                      v-for="item in s_categorys"
                      :key="item"
                      :label="item"
                      :value="item">
                  </el-option>
                </el-select>
              </el-form-item>
            </el-col>
          </el-row>

          <el-row>
            <el-col :span="6">
              <el-form-item label="学院：" prop="departmentId">
                <el-select v-model="student.departmentId"
                           placeholder="学院" size="mini" style="width: 150px">
                  <el-option
                      v-for="item in departments"
                      :key="item.id"
                      :label="item.name"
                      :value="item.id">
                  </el-option>
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="6">
              <el-form-item label="专业：" prop="majorId">
                <el-select v-model="student.majorId"
                           placeholder="专业" size="mini" style="width: 150px">
                  <el-option
                      v-for="item in majors"
                      :key="item.id"
                      :label="item.name"
                      :value="item.id">
                  </el-option>
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="6">
              <el-form-item label="惩处信息：" prop="punishment_info">
                <el-input size="mini" style="width: 120px" v-model="student.punishment_info" placeholder="请输入惩处信息"
                          prefix-icon="el-icon-edit"></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="6">
              <el-form-item label="惩处类别：" prop="punishment_type">
                <el-select v-model="student.punishment_type"
                           placeholder="学生类别" size="mini" style="width: 150px">
                  <el-option
                      v-for="item in punishment_types"
                      :key="item"
                      :label="item"
                      :value="item">
                  </el-option>
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="6">
              <el-form-item label="惩处日期：" prop="punishment_time">
                <el-date-picker
                    v-model="student.punishment_time"
                    size="mini"
                    type="date"
                    value-format="yyyy-MM-dd"
                    style="width: 130px"
                    placeholder="惩处日期">
                </el-date-picker>
              </el-form-item>
            </el-col>
            <el-col :span="6">
              <el-form-item label="惩处部门：" prop="punishment_department">
                <el-input size="mini" style="width: 120px" v-model="student.punishment_department" placeholder="请输入惩处部门"
                          prefix-icon="el-icon-edit"></el-input>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="10">
              <el-form-item label="此信息数据hash值：" prop="hash_code">
                <el-input size="mini" style="width: 500px" v-model="student.hash_code" disabled placeholder="hash值未生成">
                </el-input>
              </el-form-item>
            </el-col>
            <el-col :span="10">
              <el-form-item label="上一个学生信息数据hash值：" prop="previousHash">
                <el-input size="mini" style="width: 500px" v-model="student.previousHash" disabled placeholder="hash值未生成">
                </el-input>
              </el-form-item>
            </el-col>
          </el-row>
        </el-form>
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="doAddStudent">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
const sha256 = require("js-sha256").sha256
export default {
  name: "stuPunish",
  data() {
    return {
      initHashCode:[],
      searchValue: {
        majorId: null,
        nationId: null,
        departmentId: null,
        beginDateScope: null
      },
      showAdvanceSearchVisible: false,//高级搜索特效
      headers: {
        Authorization: window.sessionStorage.getItem('tokenStr')
      },
      importDataBtnText: '导入数据',
      importDataBtnIcon: 'el-icon-upload2',
      importDataDisabled: false,//禁止连续导入
      title: '',
      studentInfos: [],
      loading: false,
      total: 0,
      currentPage: 1,
      size: 10,
      studentName: '',//查询单个学生姓名
      dialogVisible: false,//弹出框
      nations: [],//民族
      departments: [],//学院
      majors: [],//专业
      punishment_types:['校级','市级','省级','国家级'],
      school_areas: ['大学城校区', '尖顶坡校区'],
      is_leavings:['是','否'],
      is_livings:['是','否'],
      s_types:['专科教学','本科教学','硕士教学','博士教学'],
      s_levels:['专科','本科','硕士','博士'],
      s_categorys:['普通专科生','普通本科生','普通硕士生','普通博士生'],
      learn_forms:['普通全日制','普通半日制'],
      statues:['在校','休学','离校','注册'],
      student: {
        id:null,
        s_number: '',
        name: '',
        nationId: null,
        sex: '',
        grade: '',
        s_level: '',
        s_category: '',
        departmentId: null,
        majorId: null,
        punishment_info: '',
        punishment_type: '',
        punishment_time: '',
        punishment_department:'',
        hash_code: '',
        previousHash:''
      },
      rules: {
        s_number: [{
          required: true, message: '请输入学号', trigger:
              'blur'
        }],
        name: [{
          required: true, message: '请输入学生姓名', trigger:
              'blur'
        }],
        sex: [{
          required: true, message: '请输入学生性别', trigger:
              'blur'
        }],
        nationId: [{
          required: true, message: '请输入民族', trigger:
              'blur'
        }],

        grade: [{
          required: true, message: '请输入所在年级', trigger:
              'blur'
        }],

        s_level: [{
          required: true, message: '请输入学历层次', trigger:
              'blur'
        }],
        s_category: [{
          required: true, message: '请输入学生类别', trigger:
              'blur'
        }],
        departmentId: [{
          required: true, message: '请输入学院名称',
          trigger: 'blur'
        }],
        majorId: [{
          required: true, message: '请输入专业', trigger:
              'blur'
        }],
        punishment_info: [{
          required: true, message: '请输入惩处信息',
          trigger: 'blur'
        }],
        punishment_type: [{
          required: true, message: '请输入惩处类型',
          trigger: 'blur'
        }],
        punishment_time: [{
          required: true, message: '请输入惩处时间',
          trigger: 'blur'
        }],
        punishment_department: [{
          required: true, message: '请输入惩处部门',
          trigger: 'blur'
        }]
      }
    }
  },
  mounted() {
    this.initStuInfos();
    this.initData();

  },
  methods: {
    computeHashCode(data){
      this.$confirm('此操作将生成该【' + data.name + '】信息的hash值, 是否继续?', '提示:请注意不要生成最后一个学生的hash值!', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: ''
      }).then(() => {
        this.getRequest('/student/punish/compute/' + data.id).then(resp => {
          if (resp) {
            this.initStuInfos();
            this.initHashCode.push(resp);
          }
        });
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消操作'
        });
      });
    },
    NOShowAdvanceSearchView(){
      this.showAdvanceSearchVisible = !this.showAdvanceSearchVisible;
      this.initStuInfos();
      this.initMajors();
      this.initDepartments();
    },
    showAdvanceSearchView() {
      this.showAdvanceSearchVisible = !this.showAdvanceSearchVisible;
      this.searchValue = {
        majorId: null,
        nationId: null,
        departmentId: null,
        beginDateScope: null
      }
      this.initMajors();
      this.initDepartments();
    },
    onError() {
      this.importDataBtnText = '导入数据';
      this.importDataBtnIcon = 'el-icon-upload2';
      this.importDataDisabled = false;
    },
    onSuccess() {
      this.importDataBtnText = '导入数据';
      this.importDataBtnIcon = 'el-icon-upload2';
      this.importDataDisabled = false;
      this.initStuInfos();
    },
    beforeUpload() {
      this.importDataBtnText = '正在导入';
      this.importDataBtnIcon = 'el-icon-loading';
      this.importDataDisabled = true;
    },
    exportData() {
      this.downloadRequset('/student/punish/export');
    },
    showEditStudentView(data) {//编辑学生信息
      this.title = '编辑学生惩处信息';
      this.student = data;
      this.dialogVisible = true;
      this.initDepartments();
      this.initMajors();
    },
    deleteStudent(data) {//删除学生信息
      this.$confirm('此操作将永久删除该【' + data.name + '】, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.deleteRequest('/student/punish/' + data.id).then(resp => {
          if (resp) {
            this.initStuInfos();
          }
        });
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        });
      });
    },
    doAddStudent() {//编辑学生信息 确定按钮
      if (this.student.id) {
        this.$refs['studentForm'].validate(valid => {
          if (valid) {
            this.putRequest('/student/punish/', this.student).then(resp => {
              if (resp) {
                this.dialogVisible = false;
                this.initStuInfos();
              }
            });
          }
        })
      } else {
        this.$refs['studentForm'].validate(valid => {
          if (valid) {
            this.postRequest('/student/punish/', this.student).then(resp => {
              if (resp) {
                this.dialogVisible = false;
                this.initStuInfos();
              }
            })
          }
        })
      }
    },
    initData() {//添加其他数据 民族/学院/专业
      if (!window.sessionStorage.getItem("nations")) {
        this.getRequest('/student/punish/nation').then(resp => {
          if (resp) {
            this.nations = resp;
            window.sessionStorage.setItem("nations", JSON.stringify(resp));
          }
        })
      } else {
        this.nations = JSON.parse(window.sessionStorage.getItem("nations"))
      }
      //
      // if (!window.sessionStorage.getItem("departments")) {
      //   this.getRequest('/student/punish/department').then(resp => {
      //     if (resp) {
      //       this.departments = resp;
      //       window.sessionStorage.setItem("departments", JSON.stringify(resp));
      //     }
      //   })
      // } else {
      //   this.departments = JSON.parse(window.sessionStorage.getItem("departments"))
      // }
      //
      // if (!window.sessionStorage.getItem("majors")) {
      //   this.getRequest('/student/punish/major').then(resp => {
      //     if (resp) {
      //       this.majors = resp;
      //       window.sessionStorage.setItem("majors", JSON.stringify(resp));
      //     }
      //   })
      // } else {
      //   this.majors = JSON.parse(window.sessionStorage.getItem("majors"))
      // }
    },
    initDepartments(){
      this.getRequest('/student/info/department').then(resp => {
        if (resp) {
          this.departments = resp;
        }
      })
    },
    initMajors() {
      this.getRequest('/student/info/major').then(resp => {
        if (resp) {
          this.majors = resp;
        }
      })
    },
    showAddStudentView() {//添加学生按钮
      this.title = '添加新学生惩处信息';
      this.student = {
        id:null,
        s_number: '',
        name: '',
        nationId: null,
        sex: '',
        grade: '',
        s_level: '',
        s_category: '',
        departmentId: null,
        majorId: null,
        punishment_info: '',
        punishment_type: '',
        punishment_time: '',
        punishment_department:'',
        hash_code: '',
        previousHash:''
      }
      this.dialogVisible = true;
      this.initDepartments();
      this.initMajors();
    },
    sizeChange(currentSize) {//改变页面总数
      this.size = currentSize;
      this.initStuInfos();
    },
    currentChange(currentPage) {//改变页数
      this.currentPage = currentPage;
      this.initStuInfos();
    },
    initStuInfos(type) {//初始化学生数据
      this.loading = true;
      let url = '/student/punish/?currentPage=' + this.currentPage + '&size=' + this.size;
      if (type && type == 'advanced') {
        if (this.searchValue.majorId) {
          url += '&majorId=' + this.searchValue.majorId;
        }
        if (this.searchValue.nationId) {
          url += '&nationId=' + this.searchValue.nationId;
        }
        if (this.searchValue.departmentId) {
          url += '&departmentId=' + this.searchValue.departmentId;
        }
        if (this.searchValue.beginDateScope) {
          url += '&beginDateScope=' + this.searchValue.beginDateScope;
        }
      } else {
        url += '&name=' + this.studentName;
      }
      this.getRequest(url).then(resp => {
        this.loading = false;
        if (resp) {
          for (var i = 0; i < resp.data.length - 1;i++){
            var id = resp.data[i].id.toString();
            var s_number = resp.data[i].s_number.toString();
            var name = resp.data[i].name.toString();
            var nationId = resp.data[i].nationId.toString();
            var sex = resp.data[i].sex.toString();
            var grade = resp.data[i].grade.toString();
            var majorId = resp.data[i].majorId.toString();
            var departmentId = resp.data[i].departmentId.toString();
            var s_level = resp.data[i].s_level.toString();
            var s_category = resp.data[i].s_category.toString();
            var punishment_info = resp.data[i].punishment_info.toString();
            var punishment_type = resp.data[i].punishment_type.toString();
            var punishment_time = resp.data[i].punishment_time.toString();
            var punishment_department = resp.data[i].punishment_department.toString();

            this.initHashCode.push(sha256(
                id + s_number
                + name + nationId
                +grade + sex
                + majorId + departmentId
                +s_level + s_category
                +punishment_info + punishment_type
                +punishment_time + punishment_department
            ))

          }
          for(var i =0; i < resp.data.length - 1; i++){
            //console.log(resp.data[i+1].previousHash)
            //console.log(this.initHashCode[i])
            if (resp.data[i+1].previousHash == this.initHashCode[i]){
              this.studentInfos = resp.data;
              this.total = resp.total;
            }else{
              //alert("此类学生数据已被修改，请立刻联系数据库管理人员进行数据排查!")
              this.studentInfos = resp.data;
              this.total = resp.total;
              this.$message({
                type: 'warning',
                message: '【'+resp.data[i].name+'】' +'等学生数据已被恶意修改，请立刻联系数据库管理人员进行数据排查!'
              });
              break;
            }
          }

          this.studentInfos = resp.data;
          this.total = resp.total;
        }
      })
    }
  }
}
</script>

<style scoped>

</style>
